package studentdemo.ui;

import studentdemo.modul.Course;
import studentdemo.server.CourseService;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.util.List;

public class CoursePanel extends JPanel {
    private CourseService courseService = new CourseService();
    private JTable table;
    private DefaultTableModel tableModel;
    private JTextField searchIdField, searchNameField;
    private JButton searchBtn, addBtn, editBtn, deleteBtn, prevBtn, nextBtn, refreshBtn;
    private int currentPage = 1;
    private final int pageSize = 10;
    private int totalPage = 1;

    public CoursePanel() {
        setLayout(new BorderLayout());
        // 顶部查询区
        JPanel searchPanel = new JPanel();
        searchPanel.add(new JLabel("课程编号:"));
        searchIdField = new JTextField(8);
        searchPanel.add(searchIdField);
        searchPanel.add(new JLabel("课程名称:"));
        searchNameField = new JTextField(8);
        searchPanel.add(searchNameField);
        searchBtn = new JButton("查询");
        searchPanel.add(searchBtn);
        refreshBtn = new JButton("刷新");
        searchPanel.add(refreshBtn);
        add(searchPanel, BorderLayout.NORTH);

        // 表格区
        String[] columns = {"课程编号", "课程名称", "开课学期", "学时", "考试方式", "学分"};
        tableModel = new DefaultTableModel(columns, 0) {
            public boolean isCellEditable(int row, int column) { return false; }
        };
        table = new JTable(tableModel);
        JScrollPane scrollPane = new JScrollPane(table);
        add(scrollPane, BorderLayout.CENTER);

        // 底部操作区
        JPanel opPanel = new JPanel();
        addBtn = new JButton("新增");
        editBtn = new JButton("修改");
        deleteBtn = new JButton("删除");
        prevBtn = new JButton("上一页");
        nextBtn = new JButton("下一页");
        opPanel.add(addBtn);
        opPanel.add(editBtn);
        opPanel.add(deleteBtn);
        opPanel.add(prevBtn);
        opPanel.add(nextBtn);
        add(opPanel, BorderLayout.SOUTH);

        // 事件绑定
        searchBtn.addActionListener(e -> searchAction());
        refreshBtn.addActionListener(e -> loadTable(currentPage));
        addBtn.addActionListener(e -> showCourseDialog(null));
        editBtn.addActionListener(e -> editCourseAction());
        deleteBtn.addActionListener(e -> deleteCourseAction());
        prevBtn.addActionListener(e -> {
            if (currentPage > 1) {
                currentPage--;
                loadTable(currentPage);
            }
        });
        nextBtn.addActionListener(e -> {
            if (currentPage < totalPage) {
                currentPage++;
                loadTable(currentPage);
            }
        });

        loadTable(1);
    }

    private void loadTable(int page) {
        tableModel.setRowCount(0);
        int count = courseService.getCourseCount();
        totalPage = (int) Math.ceil(count * 1.0 / pageSize);
        if (totalPage == 0) totalPage = 1;
        List<Course> list = courseService.getCoursesByPage(page, pageSize);
        for (Course c : list) {
            tableModel.addRow(new Object[]{
                    c.getCno(), c.getCname(), c.getSemester(), c.getHours(), c.getExam(), c.getCredit()
            });
        }
    }

    private void searchAction() {
        String cno = searchIdField.getText().trim();
        String name = searchNameField.getText().trim();
        tableModel.setRowCount(0);
        if (!cno.isEmpty()) {
            Course c = courseService.getCourseById(cno);
            if (c != null) {
                tableModel.addRow(new Object[]{
                        c.getCno(), c.getCname(), c.getSemester(), c.getHours(), c.getExam(), c.getCredit()
                });
            } else {
                JOptionPane.showMessageDialog(this, "未找到该课程编号");
            }
        } else if (!name.isEmpty()) {
            List<Course> list = courseService.getCoursesByName(name);
            for (Course c : list) {
                tableModel.addRow(new Object[]{
                        c.getCno(), c.getCname(), c.getSemester(), c.getHours(), c.getExam(), c.getCredit()
                });
            }
        } else {
            loadTable(1);
        }
    }

    private void showCourseDialog(Course course) {
        JTextField cnoField = new JTextField();
        JTextField cnameField = new JTextField();
        JTextField semesterField = new JTextField();
        JTextField hoursField = new JTextField();
        JTextField examField = new JTextField();
        JTextField creditField = new JTextField();

        if (course != null) {
            cnoField.setText(course.getCno());
            cnoField.setEditable(false);
            cnameField.setText(course.getCname());
            semesterField.setText(course.getSemester());
            hoursField.setText(String.valueOf(course.getHours()));
            examField.setText(course.getExam());
            creditField.setText(String.valueOf(course.getCredit()));
        }

        JPanel panel = new JPanel(new GridLayout(0, 2));
        panel.add(new JLabel("课程编号:")); panel.add(cnoField);
        panel.add(new JLabel("课程名称:")); panel.add(cnameField);
        panel.add(new JLabel("开课学期:")); panel.add(semesterField);
        panel.add(new JLabel("学时:")); panel.add(hoursField);
        panel.add(new JLabel("考试方式:")); panel.add(examField);
        panel.add(new JLabel("学分:")); panel.add(creditField);

        int result = JOptionPane.showConfirmDialog(this, panel, course == null ? "新增课程" : "修改课程", JOptionPane.OK_CANCEL_OPTION);
        if (result == JOptionPane.OK_OPTION) {
            try {
                String cno = cnoField.getText().trim();
                String cname = cnameField.getText().trim();
                String semester = semesterField.getText().trim();
                int hours = Integer.parseInt(hoursField.getText().trim());
                String exam = examField.getText().trim();
                int credit = Integer.parseInt(creditField.getText().trim());
                Course c = new Course(cno, cname, semester, hours, exam, credit);
                boolean success;
                if (course == null) {
                    success = courseService.addCourse(c);
                } else {
                    success = courseService.updateCourse(c);
                }
                if (success) {
                    JOptionPane.showMessageDialog(this, "操作成功");
                    loadTable(currentPage);
                } else {
                    JOptionPane.showMessageDialog(this, "操作失败");
                }
            } catch (Exception ex) {
                JOptionPane.showMessageDialog(this, "输入有误: " + ex.getMessage());
            }
        }
    }

    private void editCourseAction() {
        int row = table.getSelectedRow();
        if (row == -1) {
            JOptionPane.showMessageDialog(this, "请先选中一行");
            return;
        }
        String cno = (String) tableModel.getValueAt(row, 0);
        Course c = courseService.getCourseById(cno);
        if (c != null) {
            showCourseDialog(c);
        }
    }

    private void deleteCourseAction() {
        int row = table.getSelectedRow();
        if (row == -1) {
            JOptionPane.showMessageDialog(this, "请先选中一行");
            return;
        }
        String cno = (String) tableModel.getValueAt(row, 0);
        int confirm = JOptionPane.showConfirmDialog(this, "确定要删除课程编号为" + cno + "的课程吗？", "确认删除", JOptionPane.YES_NO_OPTION);
        if (confirm == JOptionPane.YES_OPTION) {
            boolean success = courseService.deleteCourse(cno);
            if (success) {
                JOptionPane.showMessageDialog(this, "删除成功");
                loadTable(currentPage);
            } else {
                JOptionPane.showMessageDialog(this, "删除失败");
            }
        }
    }
} 